package com.zzb.weixin.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzb.weixin.WeiXinUtil;
import com.zzb.weixin.constant.WXUrlName;
import com.zzb.weixin.listener.ListenerManager;
import com.zzb.weixin.listener.MWMessageListener;

/**
 * 处理微信服务器请求的Servlet URL地址：http://xxx/sendMsg
 * 
 * 注意：官方文档限制使用80端口！
 * 
 */
public class WinXinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * 处理微信服务器验证
	 * 
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String signature = request.getParameter(WXUrlName.SIGNATURE);// 微信加密签名
		String timestamp = request.getParameter(WXUrlName.TIME_STAMP);// 时间戳
		String nonce = request.getParameter(WXUrlName.NONCE);// 随机数
		String echostr = request.getParameter(WXUrlName.ECHO_STR);// 随机字符串
		Writer out = response.getWriter();
		if (WeiXinUtil.check(timestamp, nonce, signature)) {
			out.write(echostr);// 请求验证成功，返回随机码
		} else {
			out.write("");
		}
		out.flush();
		out.close();
	}





	/**
	 * 处理微信服务器发过来的各种消息，包括：文本、图片、地理位置、音乐等等
	 * 
	 * 
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		InputStream is  = request.getInputStream();
		OutputStream os = response.getOutputStream();
		try {
			//处理微信消息
			listenerManger.process(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//以下代码为处理微信接收的消息并自动返回指定内容的代码，具体实现内容可自行修改
	private static ListenerManager listenerManger = ListenerManager.newInstance();
	static {
		//向监听器中添加事件响应方法，可以添加多个，会遍历执行
		listenerManger.addOnHandleMessageListener(new MWMessageListener());
	}

}
